package com.fallsvc.onlinemusic.controller;

import com.fallsvc.onlinemusic.controller.enums.MusicFormatEnums;
import com.fallsvc.onlinemusic.mapper.LoveMusicMapper;
import com.fallsvc.onlinemusic.mapper.MusicMapper;
import com.fallsvc.onlinemusic.model.Music;
import com.fallsvc.onlinemusic.model.User;
import com.fallsvc.onlinemusic.tools.Constant;
import com.fallsvc.onlinemusic.tools.ResponseBodyMessage;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @auther falls_vc
 * description:
 * @date 2025/4/2  21:43
 */
@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {

    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicMapper musicMapper;
    @Resource
    private LoveMusicMapper loveMusicMapper;
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer, @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request, HttpServletResponse response) throws IOException {
//        // 1.检查是否登录
//        HttpSession session=request.getSession();
//        if(session==null||session.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
//            return new ResponseBodyMessage<>(-1,"用户未登录",false);
//        }
//
       String fileNameAndType=file.getOriginalFilename();
        // TODO 文件格式校验 验证该文件是音乐文件
        if (Strings.isEmpty(fileNameAndType)) {
            throw new RuntimeException("文件名未找到");
        }
        String suffix = fileNameAndType.substring(fileNameAndType.lastIndexOf(".") + 1);

        if (MusicFormatEnums.forName(suffix) == null) {
            log.info("\"服务器上传失败,文件不是支持的音乐文件\"");
            return new ResponseBodyMessage<>(-1,"服务器上传失败,文件不是支持的音乐文件",false);
        }


        // 2.上传到服务器

        log.info("fileNameAndType:"+fileNameAndType);
        // 获得title
        int index=fileNameAndType.lastIndexOf(".");
        String title=fileNameAndType.substring(0,index);

        //   用歌手名和title 查询歌曲是否存在
        Music music=new Music();
        music.setTitle(title);
        music.setSinger(singer);

        try {
            Music m=musicMapper.selectMusicByTitleAndSinger(music);
            if(m!=null)
                return new ResponseBodyMessage<>(-1,"服务器上传失败,音乐已经存在",false);
        } catch (TooManyResultsException e) {
            return new ResponseBodyMessage<>(-1,"服务器上传失败,音乐已经存在",false);
        }


        String path=SAVE_PATH+fileNameAndType;

        File dest=new File(path);
        if(!dest.exists()){
            dest.mkdir();
        }

        try{
            file.transferTo(dest);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败",false);
        }

        // 3. 准备数据，保存数据库

        HttpSession session=request.getSession();
        User user=(User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        music.setUserid(user.getId());

        music.setUrl("/music/get?path="+title);

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        music.setTime(simpleDateFormat.format(new Date()));

        try {
            int ret= musicMapper.insertMusic(music);
            if(ret==1){
                // 跳转页面
                response.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(0,"数据库成功上传",true);

            }else{
                dest.delete();// 删除服务器上传音乐
                return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
            }
        } catch (BindingException e) {
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
        }

    }

    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file=new File(SAVE_PATH+path);
        byte[] a=null;
        try{
            a= Files.readAllBytes(file.toPath());
            if(a==null){
                return ResponseEntity.badRequest().build();// 400
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            log.info("播放音乐异常：e:{}",e);
            return ResponseEntity.badRequest().build();
        }
    }


    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        int iid=Integer.parseInt(id);
        // 1. 音乐是否存在
        Music music=musicMapper.selectMusicById(iid);
        if(music==null){
            log.info("没有这个id音乐：id："+id);
            return new ResponseBodyMessage<>(-1,"数据库没有该音乐",false);
        }
        // 2.存在进行删除
        int ret= musicMapper.deleteMusicById(iid);
        if(ret==1){
            // 删除服务器上的
            String path=SAVE_PATH+music.getTitle()+".mp3";

            File file=new File(path);
            log.info("删除服务器音乐时当前音乐路径："+path);
            if(file.delete()){
                // 删除lovemusic表里数据
                Integer integer = loveMusicMapper.deleteByMusicId(iid);
                if(integer!=null) {
                    return new ResponseBodyMessage<>(1,"音乐删除成功",true);
                }else{
                    return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
                }

            }else {
                return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
            }
        }else{
            return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
        }

    }

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id){
        log.info("所有id：{}",id);
        int count=0;
        for(int iid:id){
            // 1. 音乐是否存在
            Music music=musicMapper.selectMusicById(iid);
            if(music==null){
                log.info("没有这个id音乐：id："+id);
                return new ResponseBodyMessage<>(-1,"数据库没有该音乐",false);
            }

            // 2.存在进行删除
            int ret= musicMapper.deleteMusicById(iid);
            if(ret==1){
                // 删除服务器上的
                String path=SAVE_PATH+music.getTitle()+".mp3";

                File file=new File(path);
                log.info("删除服务器音乐时当前音乐路径："+path);
                if(file.delete()){
                    log.info("删除成功音乐id:"+iid);
                    // TODO 优化
                    Integer integer = loveMusicMapper.deleteByMusicId(iid);

                    count++;
                }else {
                    return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
            }
        }

        if(count==id.size()){

            return new ResponseBodyMessage<>(1,"音乐删除成功",true);
        }else{
            return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
        }
    }

    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        log.info("查询音乐字符串："+musicName);
        List<Music> musicList=null;
        if(!StringUtils.hasLength(musicName)){
            musicList=musicMapper.findMusic();
        }else {
            musicList=musicMapper.findMusicByName(musicName);
        }
        log.info("查询到的所有音乐：{}",musicList);
        return new ResponseBodyMessage<>(0,"查询到音乐",musicList);
    }


 }
